import React, { Component } from 'react';
import moment from 'moment'; //time格式工厂
import style from './Organization.less';
import { connect } from 'dva';
import { FormattedMessage, formatMessage } from 'umi/locale'; //此方法引入的数据可以在src/locales中配置
import {
  Button,
  Input,
  DatePicker,
  Form,
  Row,
  Col,
  Table,
  Modal,
  Select,
  Card,
  PageHeader,
  Alert,
  Pagination,
  Upload,
  message,
  Icon,
  TreeSelect,
} from 'antd';

//日期插件
const { MonthPicker, RangePicker, WeekPicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';

//表单
const FormItem = Form.Item;
const { TextArea } = Input;

//所属租户选择框
const Option = Select.Option;
//多级选择树
const TreeNode = TreeSelect.TreeNode;

//命名空间
const namespace = 'Organization';
const dept_nickname =  formatMessage({ id: 'iot.organization.dept_nickname'});
const mapDispatchToProps = function(dispatch) {
  return {
    dispatch: dispatch,
  };
};

@connect(mapDispatchToProps)
@Form.create()
class ModalBox extends Component {
  constructor(props) {
    super(props);
  }

  state = {
    deptsTree: [],
    //确定按钮状态
    loading: false,
  };

  //所属组织机构树渲染
  renderTreeNodes = data =>
    data.map(item => {
      if (item.depts) {
        return (
          <TreeNode title={item.dept_name} key={item.dept_id} dataRef={item} value={item.dept_id}>
            {this.renderTreeNodes(item.depts)}
          </TreeNode>
        );
      } else {
        return (
          <TreeNode title={item.dept_name} key={item.dept_id} dataRef={item} value={item.dept_id} />
        );
      }
    });

  //项目创建部门树渲染
  createDept = data =>
    data.map(item => {
      if (item.depts) {
        return (
          <TreeNode title={item.dept_name} key={item.dept_id} dataRef={item} value={item.dept_id}>
            {this.createDept(item.depts)}
          </TreeNode>
        );
      } else {
        return (
          <TreeNode title={item.dept_name} key={item.dept_id} dataRef={item} value={item.dept_id} />
        );
      }
    });

  //根据租户内容查询组织机构信息的方法
  searchDept = function(value, option) {
    this.props.dispatch({
      type: `${namespace}/deptsTree`,
      payload: {
        tenant_id: value,
      },
      callback: res => {
        this.setState({
          deptsTree: res.list,
        });
      },
    });
  };

  //点击确定，编辑后的回调方法
  onOk = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        //基础数据
        let subData = {
          tenant_id: this.props.fatherProps.key,
          ...values,
        };
        const nowNode = this.props.nowNode;

        //不是父级元素时
        if (this.props.selectedKeys_key !== 'father') {
          //层级判断
          let dept_level = 0;
          for (let i = 0; i < nowNode.pos.length; i++) {
            if (nowNode.pos[i].charAt() === '-') {
              dept_level++;
            }
          }
          dept_level -= 1;

          //增加pid和层级
          if (this.props.modalFlag == 'brother') {
            //判断是否是除了租户外的顶级
            if (nowNode.dataRef.dept_pid == '' || nowNode.dataRef.dept_pid == null) {
              subData.dept_pid = '';
            } else {
              subData.dept_pid = nowNode.dataRef.dept_pid;
            }
            subData.dept_level = dept_level;
          }
          if (this.props.modalFlag == 'children') {
            subData.dept_pid = nowNode.dataRef.dept_id;
            subData.dept_level = dept_level + 1;
          }
          //编辑时需要dept_id,新建的时候需要tenant_id
          if (this.props.modalFlag == 'edit') {
            subData.dept_id = nowNode.dataRef.dept_id;
          }
        } else {
          subData.dept_pid = '';
          subData.dept_level = 1;
        }

        if (this.props.modalFlag != 'edit') {
          //避免重复点击确定按钮
          this.setState({
            loading: true,
          });
          this.loadingTimer = setTimeout(() => {
            this.setState({
              loading: false,
            });
          }, 500);
          //新增表单请求
          this.props.dispatch({
            type: `${namespace}/addBegin`,
            payload: {
              values: subData,
            },
            callback: res => {
              if (res.return_code === 'SUCCESS') {
                //关闭模态框
                this.props.childModalChangeModalState({
                  visible: true,
                });
                message.success('新增成功');

                //重置表单
                this.props.form.resetFields();

                //代入当前租户状态重新查询一次树
                this.props.dispatch({
                  type: `${namespace}/deptsTree`,
                  payload: {
                    tenant_id: this.props.fatherProps.key,
                  },
                  callback: res => {
                    this.props.setTreeMothed(res.data);
                  },
                });
              }
            },
          });
        } else {
          //避免重复点击确定按钮
          this.setState({
            loading: true,
          });
          this.loadingTimer = setTimeout(() => {
            this.setState({
              loading: false,
            });
          }, 500);
          //修改表单请求
          this.props.dispatch({
            type: `${namespace}/editBegin`,
            payload: {
              values: subData,
            },
            callback: res => {
              if (res.return_code === 'SUCCESS') {
                //关闭模态框
                this.props.childModalChangeModalState({
                  visible: true,
                });
                message.success('修改成功');

                //重置表单
                this.props.form.resetFields();

                //代入当前租户状态重新查询一次树
                this.props.dispatch({
                  type: `${namespace}/deptsTree`,
                  payload: {
                    tenant_id: this.props.fatherProps.key,
                  },
                  callback: res => {
                    this.props.clearMothed(res.data);
                  },
                });
              }
            },
          });
        }
      }
    });
  };

  componentWillUnmount(){
    //清除定时器，防止内存泄露
    clearTimeout(this.loadingTimer);
  }

  render() {
    const { dispatch, form } = this.props;
    const {
      form: { getFieldDecorator, getFieldValue, getFieldsValue, setFieldsValue, resetFields },
      nowRow,
    } = this.props;

    //规则就是用来打破的

    const dept_name_rules = {
      rules: [
        {
          required: true,
          message: `${dept_nickname}名称是一个必填项`,
        },
        {
          min: 0,
          max: 20,
          message: `${dept_nickname}名称应在20个字符内`,
        },
        {
          pattern: /^[^ ]+$/,
          whitespace: true,
          message: '不能使用空格',
        },
      ],
      initialValue:
        this.props.modalFlag === 'edit' ? this.props.nowNode.dataRef.dept_name : undefined,
    };
    const dept_abbr_rules = {
      rules: [
        {
          required: true,
          message: `${dept_nickname}简称必须填写`,
        },
        {
          min: 0,
          max: 20,
          message: `${dept_nickname}简称应在20个字符内`,
        },
        {
          pattern: /^[^ ]+$/,
          whitespace: true,
          message: '不能使用空格',
        },
      ],
      initialValue:
        this.props.modalFlag === 'edit' ? this.props.nowNode.dataRef.dept_abbr : undefined,
    };
    const dept_code_rules = {
      rules: [
        {
          required: true,
          pattern: /^[^ ]+$/,
          whitespace: true,
          max: 50,
          message: `请输入50位以下${dept_nickname}代码(不能包含空格)`,
        },
        {
          pattern: /^[0-9a-zA-Z_\\-]{1,}$/,
          message: '禁止输入中文',
        },
      ],
      initialValue:
        this.props.modalFlag === 'edit'
          ? this.props.nowNode
            ? this.props.nowNode.dataRef.dept_code
            : undefined
          : undefined,
    };
    const person_rules = {
      rules: [
        {
          min: 0,
          max: 50,
          message: '法人应在50个字符内',
        },
        {
          pattern: /^[^ ]+$/,
          whitespace: true,
          message: '不能使用空格',
        },
      ],
      initialValue:
        this.props.modalFlag === 'edit'
          ? this.props.nowNode
          ? this.props.nowNode.dataRef.legal_person
          : undefined
          : undefined,
    };
    const status_rules = {
      rules: [
        {
          min: 0,
          max: 50,
          message: '公司状态应在50个字符内',
        },
        {
          pattern: /^[^ ]+$/,
          whitespace: true,
          message: '不能使用空格',
        },
      ],
      initialValue:
        this.props.modalFlag === 'edit'
          ? this.props.nowNode
          ? this.props.nowNode.dataRef.company_state
          : undefined
          : undefined,
    }
    return (
      <div>
        <Modal
          visible={this.props.visible}
          title={this.props.modalFlag === 'edit' ? '修改节点信息' : '新建一个节点'}
          onCancel={() => this.props.cancel(this.props.form)}
          destroyOnClose={true}
          maskClosable={false}
          bodyStyle={{
            width: 420,
          }}
          width="550px"
          footer={[
            <Button key="back" onClick={() => this.props.cancel(this.props.form)}>
              取消
            </Button>,
            <Button
            key="submit"
            type="primary"
            loading={this.state.loading}
            onClick={this.onOk}
            >
              提交
            </Button>,
          ]}
        >
          <Form layout="inline">
            {/* 行1 */}
            <div className={style['motal-line']}>
              <div className={style['every-block']}>
                <p className={style.p1}>
                  <span className={style.star}>*</span>
                  {formatMessage({ id: 'iot.organization.modal_box.dept_name' })}：
                </p>
                <Form.Item style={{ marginBottom: 0 }}>
                  {getFieldDecorator('dept_name', dept_name_rules)(
                    <Input className={style['input-box']} />
                  )}
                </Form.Item>
              </div>
            </div>
            {/* 行2 */}
            <div className={style['motal-line']}>
              <div className={style['every-block']}>
                <p className={style.p1}>
                  <span className={style.star}>*</span>
                  {formatMessage({ id: 'iot.organization.modal_box.dept_abbr' })}：
                </p>
                <Form.Item style={{ marginBottom: 0 }}>
                  {getFieldDecorator('dept_abbr', dept_abbr_rules)(
                    <Input className={style['input-box']} />
                  )}
                </Form.Item>
              </div>
            </div>
            {/* 行3 */}
            <div className={style['motal-line']}>
              <div className={style['every-block']}>
                <p className={style.p1}>
                  <span className={style.star}>*</span>
                  {formatMessage({ id: 'iot.organization.modal_box.dept_code' })}：
                </p>
                <Form.Item style={{ marginBottom: 0 }}>
                  {getFieldDecorator('dept_code', dept_code_rules)(
                    <Input className={style['input-box']} />
                  )}
                </Form.Item>
              </div>
            </div>
            <div className={style['motal-line']}>
              <div className={style['every-block']}>
                <p className={style.p1}>
                  {formatMessage({ id: 'iot.organization.modal_box.person' })}：
                </p>
                <Form.Item style={{ marginBottom: 0 }}>
                  {getFieldDecorator('legal_person', person_rules)(
                    <Input className={style['input-box']} />
                  )}
                </Form.Item>
              </div>
            </div>
            <div className={style['motal-line']}>
              <div className={style['every-block']}>
                <p className={style.p1}>
                  {formatMessage({ id: 'iot.organization.modal_box.status' })}：
                </p>
                <Form.Item style={{ marginBottom: 0 }}>
                  {getFieldDecorator('company_state', status_rules)(
                    <Input className={style['input-box']} />
                  )}
                </Form.Item>
              </div>
            </div>
          </Form>
        </Modal>
      </div>
    );
  }
}

export default ModalBox;
